package com.hongye.es.service;


import com.alibaba.fastjson.JSON;
import com.hongye.common.entity.BrokerEntity;
import com.hongye.common.entity.RentHouseEntity;
import com.hongye.es.feign.RentHouseFeign;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class EsHouseService {
    @Autowired
    private RentHouseFeign rentHouseFeign;
    @Autowired
    private RestHighLevelClient restHighLevelClient;


    public void add(BrokerEntity brokerEntity) throws IOException {
        //把集合放入es中
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");

        bulkRequest.add(new IndexRequest("ycy")
                                .source(JSON.toJSONString(brokerEntity), XContentType.JSON)
        );


        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
    }

    public Boolean addEs() throws IOException {
        //房子集合
        List<RentHouseEntity> list = rentHouseFeign.list();
        //把集合放入es中
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");


        for (RentHouseEntity entity : list) {
            //只有未加入的房源才能加入es
            bulkRequest.add(
                        new IndexRequest("ycy")
                                .source(JSON.toJSONString(entity), XContentType.JSON)
            );
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }




    //获取数据加高亮
    public List<Map<String,Object>> searchPageHighlightBuilder(String keyword, int page, int size) throws Exception {
        if(page<=1){
            page = 1;
        }
        /*if (size  >  20){
            size=20;
        }*/
        //对ycy索引进行 条件搜索
        SearchRequest searchRequest = new SearchRequest("ycy");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //分页
        sourceBuilder.from(page);
        sourceBuilder.size(size);
        if(!"".equals(keyword)){
            //精确匹配  termQuery

            //MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("deconration", keyword);
            //MatchQueryBuilder matchQueryBuilder2 = QueryBuilders.matchQuery("desciption", keyword);
            MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(keyword, "rentHouseTitle");


            sourceBuilder.query(multiMatchQueryBuilder);
            //sourceBuilder.query(matchQueryBuilder2);
            sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

            //高亮
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("rentHouseTitle");
            //highlightBuilder.requireFieldMatch(false);
            highlightBuilder.preTags("<span style='color:red'>");
            highlightBuilder.postTags("</span>");
            sourceBuilder.highlighter(highlightBuilder);
            //执行搜索
            searchRequest.source(sourceBuilder);
        }
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //解析结果
        List<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit documentFields : search.getHits().getHits()) {

            //解析高亮
            Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
            HighlightField deconration = highlightFields.get("rentHouseTitle");
          /*  HighlightField desciption = highlightFields.get("desciption");
            HighlightField towards = highlightFields.get("towards");*/
            HashMap<String,HighlightField> map=new HashMap<>();
            map.put("deconration",deconration);
           /* map.put("desciption",desciption);
            map.put("towards",towards);*/
            list.add( HighlightFieldsUtils(map,documentFields));
        }
        return list;
    }

    public static  Map<String, Object> HighlightFieldsUtils(HashMap<String,HighlightField> map,SearchHit documentFields){
        Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
        for(String key:map.keySet()){
            if (map.get(key)!=null){
                Text[] fragments = map.get(key).fragments();
                String a = "";
                for (Text text : fragments) {
                    a += text;
                }
                sourceAsMap.put(key,a);
            }
        }
        return sourceAsMap;
    }

    public List<Map<String,Object>> searchPage(String key, int pageNum , int pageSize) throws IOException {

        if (pageNum<=1){
            pageNum=1;
        }

        //条件搜索
        SearchRequest searchRequest = new SearchRequest("ycy");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //分页
        sourceBuilder.from(pageNum);
        sourceBuilder.size(pageSize);
        //传输条件不为空
        if(!"".equals(key)){
            MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(key, "rentHouseTitle");
            sourceBuilder.query(multiMatchQueryBuilder);
            //sourceBuilder.query(termQueryBuilder2);
            sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
            //执行搜索
            searchRequest.source(sourceBuilder);
        }
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //解析结果
        List<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit documentFields : search.getHits()) {
            list.add(documentFields.getSourceAsMap());
        }
        return list;
    }


}
